package com.gen.com;

import java.util.ArrayList;

import com.ouken.com.LoginActivity;
import com.ouken.com.R;
import com.ouken.com.RoomlistActivity;
import com.gen.asynTask.*;
import com.gen.service.RefreshGameRoomPlayerService;
import com.gen.tool.AlertDialog_ok;
import com.gen.tool.AlertDialog_ok_cancel;
import com.gen.tool.PlayerInfo;
import com.gen.tool.SoundPlayer;
//import com.ouken.tool.MplayerTool;
import com.ouken.tool.MyApp;
import com.vick.com.ChallengerwaitingActivity;
import com.vick.com.DrawingActivity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.IBinder;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.ImageView;

public class GameRoomPlayerActivity extends Activity {
	
	/**------------------elements define area--------------------------*/
	private MyApp appState;
	private SharedPreferences userInfo;
	//private MplayerTool mplayerTool ;
	private TextView roomName;
	private TextView memNum;
	private ImageView my_image;
	private TextView myName;
	private TextView myScore;
	private ImageView userImage[] = new ImageView[4];
	private TextView user_name[] = new TextView[4];
	private TextView user_Score[] = new TextView[4];
	private TextView user_ready[] = new TextView[4];
	private ImageView user_crown[] = new ImageView[4];
	private ProgressBar user_pgbar[] = new ProgressBar[4];
	
	private Button but_getReady;
	private Button but_unReady;
	private Button but_quit;
	
	private static final char READY = '0';
	private static final char UNREADY = '1';
	private static final char EMPTY = '2';
	private static final char INACTIVE = '3';
	private static final char MANAGER = '4';
	
	private AlertDialog dialogKicked;
	/**------------------elements define area over--------------------------*/
	
	private Context context;
	private GameRoomPlayerUpdateReceiver gameRoomPlayerUpdateReceiver;
	private RefreshGameRoomPlayerService refreshGameRoomPlayerService = null;
	private IntentFilter filter;
	private Intent intentToRefreshService;
	
	private ServiceConnection connection = new ServiceConnection(){

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			refreshGameRoomPlayerService = ((RefreshGameRoomPlayerService.LocalBinder) service).getService();
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			refreshGameRoomPlayerService = null;
		}
		
	};
	
	/**-----------------initview when created-----------------*/
	private void initView(){
	
		userInfo  = getSharedPreferences("user_info", 0);
		appState = ((MyApp)getApplicationContext());
		appState.setGRcounterZ();
		//appState.setMusic(userInfo.getString("MUSIC", "ON").equals("ON"));
		appState.setListActivities(new ArrayList());
		appState.addActivity(GameRoomPlayerActivity.this);
		
		roomName = (TextView)findViewById(R.id.gameRoomPlayerActivity_textView_roomName);
        memNum = (TextView)findViewById(R.id.gameRoomPlayerActivity_textView_memnum);
        my_image = (ImageView)findViewById(R.id.gameRoomPlayerActivity_imageView_imageMe);
        myName = (TextView)findViewById(R.id.gameRoomPlayerActivity_textView_myName);
    	myScore = (TextView)findViewById(R.id.gameRoomPlayerActivity_textView_myScore);
    	userImage[0] = (ImageView)findViewById(R.id.gameRoomPlayerActivity_imageView_imageUser1);
    	user_name[0] = (TextView)findViewById(R.id.gameRoomPlayerActivity_textView_user1Name);
    	user_Score[0] = (TextView)findViewById(R.id.gameRoomPlayerActivity_textView_user1Score);
    	user_ready[0] = (TextView)findViewById(R.id.gameRoomPlayerActivity_textView_user1Ready);
    	user_crown[0] = (ImageView)findViewById(R.id.gameRoomPlayerActivity_imageView_user1Crown);
    	userImage[1] = (ImageView)findViewById(R.id.gameRoomPlayerActivity_imageView_imageUser2);
    	user_name[1] = (TextView)findViewById(R.id.gameRoomPlayerActivity_textView_user2Name);
    	user_Score[1] = (TextView)findViewById(R.id.gameRoomPlayerActivity_textView_user2Score);
    	user_ready[1] = (TextView)findViewById(R.id.gameRoomPlayerActivity_textView_user2Ready);
    	user_crown[1] = (ImageView)findViewById(R.id.gameRoomPlayerActivity_imageView_user2Crown);
    	userImage[2] = (ImageView)findViewById(R.id.gameRoomPlayerActivity_imageView_imageUser3);
    	user_name[2] = (TextView)findViewById(R.id.gameRoomPlayerActivity_textView_user3Name);
    	user_Score[2] = (TextView)findViewById(R.id.gameRoomPlayerActivity_textView_user3Score);
    	user_ready[2] = (TextView)findViewById(R.id.gameRoomPlayerActivity_textView_user3Ready);
    	user_crown[2] = (ImageView)findViewById(R.id.gameRoomPlayerActivity_imageView_user3Crown);
    	userImage[3] = (ImageView)findViewById(R.id.gameRoomPlayerActivity_imageView_imageUser4);
    	user_name[3] = (TextView)findViewById(R.id.gameRoomPlayerActivity_textView_user4Name);
    	user_Score[3] = (TextView)findViewById(R.id.gameRoomPlayerActivity_textView_user4Score);
    	user_ready[3] = (TextView)findViewById(R.id.gameRoomPlayerActivity_textView_user4Ready);
    	user_crown[3] = (ImageView)findViewById(R.id.gameRoomPlayerActivity_imageView_user4Crown);
    	user_pgbar[0] = (ProgressBar)findViewById(R.id.gameRoomPlayerActivity_loading_process_dialog_progressBar1);
    	user_pgbar[1] = (ProgressBar)findViewById(R.id.gameRoomPlayerActivity_loading_process_dialog_progressBar2);
    	user_pgbar[2] = (ProgressBar)findViewById(R.id.gameRoomPlayerActivity_loading_process_dialog_progressBar3);
    	user_pgbar[3] = (ProgressBar)findViewById(R.id.gameRoomPlayerActivity_loading_process_dialog_progressBar4);
    	
    	but_getReady = (Button)findViewById(R.id.gameRoomPlayerActivity_button_getready);
    	but_unReady = (Button)findViewById(R.id.gameRoomPlayerActivity_button_unready);
    	but_quit = (Button)findViewById(R.id.gameRoomPlayerActivity_button_quitRoom);
        
    	but_getReady.setOnClickListener(gameRoom_listener);
    	but_unReady.setOnClickListener(gameRoom_listener);
    	but_quit.setOnClickListener(gameRoom_listener);
    	
    	but_unReady.setVisibility(View.GONE);
		but_getReady.setVisibility(View.GONE);
    	
    	user_crown[0].setVisibility(View.INVISIBLE);
    	user_crown[1].setVisibility(View.INVISIBLE);
    	user_crown[2].setVisibility(View.INVISIBLE);
    	user_crown[3].setVisibility(View.INVISIBLE);
    	
    	context = GameRoomPlayerActivity.this; 
    	//mplayerTool = new MplayerTool(GameRoomPlayerActivity.this);
	}
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gameroom_player);
        initView();
        
        /**----------owner's zone-------------**/
        roomName.setText(appState.getRoomName());
		memNum.setText(appState.getMem());
		myName.setText(appState.getNickName());
		myScore.setText(appState.getTotalScore() + "pt");
		my_image.setImageBitmap(appState.getImg());
		
		/**----------bind service-------------**/
    	intentToRefreshService = new Intent("com.serive.refreshGameRoomPlayer");
		
	    gameRoomPlayerUpdateReceiver = new GameRoomPlayerUpdateReceiver();
	    filter= new IntentFilter();
	    filter.addAction("com.gameRoomPlayerUpdateReceiver");
	    registerReceiver(gameRoomPlayerUpdateReceiver, filter);
	        
	    //bindService(new Intent(this,RefreshGameRoomPlayerService.class), connection, Context.BIND_AUTO_CREATE);
    }

	private View.OnClickListener gameRoom_listener = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			
			Button gameRoom_button = (Button)v;
			SoundPlayer.playSound(R.raw.keypress_common);
			//mplayerTool.playButtonPressed(context);
			switch(gameRoom_button.getId()){
			case R.id.gameRoomPlayerActivity_button_getready:
				new AsynGetReady(context, roomName, appState.getUserEmail()).execute();
				break;
				
			case R.id.gameRoomPlayerActivity_button_unready:
				new AsynUnReady(context, roomName, appState.getUserEmail()).execute();
				break;
				
			case R.id.gameRoomPlayerActivity_button_quitRoom:
				AlertDialog_ok_cancel myDialog = new AlertDialog_ok_cancel(GameRoomPlayerActivity.this,"Are you sure \nto quit from this room?");
	        	final AlertDialog now = myDialog.AlertDialog_ok_cancel_show();
				myDialog.getConfirm_btn_ok().setOnClickListener(new View.OnClickListener(){
					@Override  
				    public void onClick(View v) { 
						SoundPlayer.playSound(R.raw.keypress_common);
						try{
                			unbindService(connection);
                		}catch(Exception e){
                			System.out.print(e.toString());
                		}
                		now.dismiss();
                    	new AsynPlayerQuitFR(context, roomName, appState.getUserEmail()).execute();
					}
					}
				); 
				
	        	myDialog.getCancel_btn_can().setOnClickListener(new View.OnClickListener(){
					@Override  
				    public void onClick(View v) {  
						SoundPlayer.playSound(R.raw.keypress_common);
						 /* User clicked Cancel so do some stuff */
                    	now.cancel();
						} 
					}
				);
				break;
			}
		}
	};
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0){
        	SoundPlayer.playSound(R.raw.keypress_common);
        	AlertDialog_ok_cancel myDialog = new AlertDialog_ok_cancel(GameRoomPlayerActivity.this,"Are you sure \nto quit from this room?");
        	final AlertDialog now = myDialog.AlertDialog_ok_cancel_show();
        	
        	myDialog.getConfirm_btn_ok().setOnClickListener(new View.OnClickListener(){
				@Override  
			    public void onClick(View v) {  
					SoundPlayer.playSound(R.raw.keypress_common);
					try{
            			unbindService(connection);
            		}catch(Exception e){
            			System.out.print(e.toString());
            		}
            		now.dismiss();
                	new AsynPlayerQuitFR(context,roomName,appState.getUserEmail()).execute();
				}
				}
			); 
			
        	myDialog.getCancel_btn_can().setOnClickListener(new View.OnClickListener(){
				@Override  
			    public void onClick(View v) {  
					SoundPlayer.playSound(R.raw.keypress_common);
					 /* User clicked Cancel so do some stuff */
                	now.cancel();
					} 
				}
			);
        }
        return false;
    }
	
	@Override
	protected void onResume() {
		super.onResume();
		appState.setGRcounterZ();
		appState.setClearPlayerInfo();
		bindService(new Intent(this,RefreshGameRoomPlayerService.class), connection, Context.BIND_AUTO_CREATE);
		System.out.println("GameRoomPlayerActivity onResume");
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		try{
			unbindService(connection);
		}catch(Exception e){
			System.out.print(e.toString());
		}
		System.out.println("GameRoomPlayerActivity onPause");
	}
	
	@Override
	protected void onDestroy() {
		 super.onDestroy();
		 unregisterReceiver(gameRoomPlayerUpdateReceiver);
		 System.out.println("GameRoomPlayerActivity onDestroy");
		
	}

	/**-------------------do refresh ope-------------*/
	public class GameRoomPlayerUpdateReceiver extends BroadcastReceiver{
	    
		@Override
		public void onReceive(Context arg0, Intent arg1) {
			System.out.println("I'm GameRoomPlayerActivity reciever");
			
			String action = arg1.getAction();
			Intent intentToNewAct;
			
			//do update
			if(action.equals("com.gameRoomPlayerUpdateReceiver")){
				Bundle bundle = arg1.getExtras();
				if(bundle !=null){
					
					String changes = bundle.getString("changes");
					StringBuffer changesCopy = new StringBuffer(changes);
					ArrayList<PlayerInfo> player = new ArrayList<PlayerInfo>(appState.getPlayerList());
					PlayerInfo tempPlayer = new PlayerInfo();
					
					
		        	
						
					//----------check if refresh----------//
						//_____________check owner____________//
						switch(changes.charAt(0)){						
						case '1':
							//*******changed state**********//
							if(player.get(0).getState().charAt(0) == READY)
							{
								but_unReady.setVisibility(View.VISIBLE);
								but_getReady.setVisibility(View.GONE);
							}
							else
							{
								but_unReady.setVisibility(View.GONE);
								but_getReady.setVisibility(View.VISIBLE);
							}
							break;
							
						case '2':
							//*******owner changed to manager**********//
							System.out.print("Player changed to manager");
							intentToNewAct = new Intent(context, GameRoomManagerActivity.class); 
							intentToNewAct.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
							context.startActivity(intentToNewAct);
							GameRoomPlayerActivity.this.finish();
							overridePendingTransition(0, 0);
							return;
							
						case '3':
							//*******started the game**********//
							if(player.get(0).getRole().equals("provider")){
								System.out.print("Started provider's page");
								intentToNewAct = new Intent(context, DrawingActivity.class); 
								intentToNewAct.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
								startActivity(intentToNewAct);
								GameRoomPlayerActivity.this.finish();
								overridePendingTransition(0, 0);
								return;
							}
							else{
								System.out.print("Started challenger's page");
								intentToNewAct = new Intent(context, ChallengerwaitingActivity.class); 
								intentToNewAct.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
								startActivity(intentToNewAct);
								GameRoomPlayerActivity.this.finish();
								overridePendingTransition(0, 0);
								return;
							}
						case '4':
							//************double log in************//
							try{
								unbindService(connection);
							}catch(Exception e){
								System.out.print(e.toString());
							}
							AlertDialog_ok myDialog = new AlertDialog_ok(GameRoomPlayerActivity.this,"Sorry~>.<~ \nYou have double logged in~");
							final AlertDialog doublelog = myDialog.AlertDialog_ok_show();
							myDialog.getConfirm_btn_ok().setOnClickListener(new View.OnClickListener(){
								@Override  
							    public void onClick(View v) {  
									SoundPlayer.playSound(R.raw.keypress_common);
									Intent intentNewAct = new Intent(context, LoginActivity.class);
									startActivity(intentNewAct);
									userInfo.edit().putString("AUTOLOGIN","NO").commit();
									doublelog.dismiss();
									appState.killAllActivities();
									} 
								}
							); 
							return;
						case '5':
							//************be kicked************//
							try{
								unbindService(connection);
							}catch(Exception e){
								System.out.print(e.toString());
							}
							AlertDialog_ok myDialog1 = new AlertDialog_ok(GameRoomPlayerActivity.this,"Sorry~>.<~ \nYou have been kicked~");
							final AlertDialog kicked = myDialog1.AlertDialog_ok_show();
				        	myDialog1.getConfirm_btn_ok().setOnClickListener(new View.OnClickListener(){
								@Override  
							    public void onClick(View v) {  
									SoundPlayer.playSound(R.raw.keypress_common);
									Intent intentNewAct = new Intent(context, RoomlistActivity.class);
									startActivity(intentNewAct);
									kicked.dismiss();
									GameRoomPlayerActivity.this.finish();
									} 
								}
							);  	
							return;
							
						}
						
						//----------first time refresh----------//
						if(appState.getRefreshGRcounter() == 0){	
							memNum.setText(appState.getMem());
							//*******changed state**********//
							if(player.get(0).getState().charAt(0) == READY)
							{
								but_unReady.setVisibility(View.VISIBLE);
								but_getReady.setVisibility(View.GONE);
							}
							else if(player.get(0).getState().charAt(0) == UNREADY)
							{
								but_unReady.setVisibility(View.GONE);
								but_getReady.setVisibility(View.VISIBLE);
							}
							else if(player.get(0).getState().charAt(0) == MANAGER){
								//*******owner changed to manager**********//
								System.out.print("Player changed to manager");
								intentToNewAct = new Intent(context, GameRoomManagerActivity.class); 
								intentToNewAct.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
								context.startActivity(intentToNewAct);
								GameRoomPlayerActivity.this.finish();
								overridePendingTransition(0, 0);
								return;
							}
							
							//____________set users' view__________//
							for(int i = 0; i< 4; i++)
							{
								tempPlayer = player.get(i+1);
									
								//user's state
								switch(tempPlayer.getState().charAt(0)){
									case READY:
										userImage[i].setImageBitmap(tempPlayer.getImg());
										user_name[i].setText(tempPlayer.getNickName());
										user_Score[i].setText(tempPlayer.getTotalScore()+ "pt");
										user_ready[i].setText("Ready");
										user_crown[i].setVisibility(View.GONE);
										break;
										
									case UNREADY:
										userImage[i].setImageBitmap(tempPlayer.getImg());
										user_name[i].setText(tempPlayer.getNickName());
										user_Score[i].setText(tempPlayer.getTotalScore()+ "pt");
										user_ready[i].setText("UnReady");
										user_crown[i].setVisibility(View.GONE);
										break;
											
									//change image to empty
									case EMPTY:
										userImage[i].setImageResource(R.drawable.picture);
										user_ready[i].setText(" ");
										user_name[i].setText("Empty Place");
										user_Score[i].setText(" ");
										user_crown[i].setVisibility(View.GONE);
										break;
											
									case INACTIVE:
										userImage[i].setImageResource(R.drawable.picture_x);
										user_ready[i].setText(" ");
										user_name[i].setText("Inactive Place");
										user_Score[i].setText(" ");
										user_crown[i].setVisibility(View.GONE);
										break;
											
									case MANAGER:
										userImage[i].setImageBitmap(tempPlayer.getImg());
										user_name[i].setText(tempPlayer.getNickName());
										user_Score[i].setText(tempPlayer.getTotalScore()+ "pt");
										user_ready[i].setText(" ");
										user_crown[i].setVisibility(View.VISIBLE);
										break;
								}
								user_pgbar[i].setVisibility(View.GONE);
							}
							appState.addGRcounter();
						}
					else{		
						changesCopy.setCharAt(0, '0');
						changes = changesCopy.toString();
						//_____________refresh playlist__________//
						if(changes.contains("1") || changes.contains("2") || changes.contains("3")){
							memNum.setText(appState.getMem());
							
							for (int i = 0; i < 4; i++) {
								
								tempPlayer = player.get(i+1);
								
								//already existed person, only change the state
								switch(changes.charAt(i+1)){
								case '1':
									switch(tempPlayer.getState().charAt(0)){
									case READY:
										user_ready[i].setText("Ready");
										user_crown[i].setVisibility(View.GONE);
										break;
										
									case UNREADY:
										user_ready[i].setText("UnReady");
										user_crown[i].setVisibility(View.GONE);
										break;
										
									case MANAGER:
										user_ready[i].setText(" ");
						            	user_crown[i].setVisibility(View.VISIBLE);
						            	break;
									}
									break;
									
								case '2':									
									//empty or inactive or new person
									switch (tempPlayer.getState().charAt(0)){
										case EMPTY:
											//change image to empty
											userImage[i].setImageResource(R.drawable.picture);
											user_ready[i].setText(" ");
											user_name[i].setText("Empty Place");
											user_Score[i].setText(" ");
											user_crown[i].setVisibility(View.GONE);
											break;
											
										case INACTIVE:
											userImage[i].setImageResource(R.drawable.picture_x);
											user_ready[i].setText(" ");
											user_name[i].setText("Inactive Place");
											user_Score[i].setText(" ");
											user_crown[i].setVisibility(View.GONE);
											break;
											
										case READY:
											userImage[i].setImageBitmap(tempPlayer.getImg());
											user_name[i].setText(tempPlayer.getNickName());
											user_Score[i].setText(tempPlayer.getTotalScore()+ "pt");
											user_ready[i].setText("Ready");
											user_crown[i].setVisibility(View.GONE);
											break;
											
										case UNREADY:
											userImage[i].setImageBitmap(tempPlayer.getImg());
											user_name[i].setText(tempPlayer.getNickName());
											user_Score[i].setText(tempPlayer.getTotalScore()+ "pt");
											user_ready[i].setText("UnReady");
											user_crown[i].setVisibility(View.GONE);
											break;
											
										default:
											user_crown[i].setVisibility(View.GONE);
									}
									break;
					            }//switch over
							}//for to find over
						}//refresh users over
					}//not first time update over
				}////have result over
			}//receive message over
		}//function over
	}//class over		
}

